package com.boilerCloud.controller.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.boilerCloud.dto.sys.ReqResult;
import com.boilerCloud.util.FileUtil;
import com.boilerCloud.util.StringUtil;



/**
 * SpringMVC中的文件上传 1)由于SpringMVC使用的是commons-fileupload实现,所以先要将其组件引入项目中
 * 2)在SpringMVC配置文件中配置MultipartResolver处理器(可在此加入对上传文件的属性限制)
 * 3)在Controller的方法中添加MultipartFile参数(该参数用于接收表单中file组件的内容)
 * 4)编写前台表单(注意enctype="multipart/form-data"以及<input type="file" name="****"/>)
 * PS:由于这里使用了ajaxfileupload.js实现无刷新上传,故本例中未使用表单
 */
@RestController
public class HzlqswFileUploadController{
	private static final Logger log = LoggerFactory.getLogger(HzlqswFileUploadController.class);
    
   
    
    /**
     * 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file"
     * name="myfiles"/>
     * 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
     */
   
    
    /**
     * <一句话功能简述>文件上传
     * <功能详细描述>第一步：图片上传到应用服务器temp临时文件夹
     *            第二步：图片上传到ftp上面
     *            第三步：删除temp临时文件
     * @param request
     * @param response
     * @param myfiles
     * @return [参数说明]
     * 
     * @return ReqResult [返回类型说明]
     * @throws IOException 
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/uploadFile", produces = "text/plain;charset=UTF-8")
    public ReqResult uploadInforImg(HttpServletRequest request, HttpServletResponse response,
            @RequestParam MultipartFile[] myfiles) throws IOException {
        ReqResult rst = new ReqResult();
        String originalFilename = "";
        FileOutputStream out = null;
        for (MultipartFile myfile : myfiles){
            if (myfile.isEmpty()) {
                rst.setResultCode(ReqResult.resultCode_error);
                rst.setReturnObject("文件错误");
            }else{
                //上传到应用服务器temp临时文件夹下面
                String path = "";
                try {
                    String temppath = request.getSession().getServletContext().getRealPath("/") + "temp";
                    originalFilename = myfile.getOriginalFilename();
                    path = temppath + File.separator + StringUtil.getUUID()
                            + originalFilename.substring(originalFilename.lastIndexOf("."));
                    out = new FileOutputStream(path);
                    out.write(myfile.getBytes());
                }catch (Exception e){
                    e.printStackTrace();
                }finally{
                    try {
                        out.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }                
                String result = FileUtil.upload(path);
                File file = new File(path);
                file.deleteOnExit();
                
                rst.setResultCode(ReqResult.resultCode_Success);
                rst.setReturnObject(result);
            }
        }
        return rst;
    }
    
    /**
     * 图片上传到临时文件夹，返回预览链接和文件名
     * @param request
     * @param response
     * @param myfiles
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadPicsFile", produces = "text/plain;charset=UTF-8")
    public ReqResult uploadPicsFile(HttpServletRequest request,
            @RequestParam MultipartFile[] myfiles) throws IOException
    {
    	log.info("开始上传");
        ReqResult rst = new ReqResult();
        String originalFilename = "";
        FileOutputStream out = null;
        String[] filenames=null;
        List<String[]> li=new ArrayList<String[]>();
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                rst.setResultCode(ReqResult.resultCode_error);
                rst.setReturnObject("文件错误");
            } else {
                //上传到应用服务器temp临时文件夹下面
                String path = "";
                try {
                	filenames=new String[3];
                    String temppath = request.getSession().getServletContext().getRealPath("/") + "temp";
                    File f=new File(temppath);
                    if(!f.isDirectory()){
                    	f.mkdir();
                    }
                    originalFilename = myfile.getOriginalFilename();
                    filenames[0]=originalFilename.substring(0, originalFilename.indexOf("."));
                    originalFilename=StringUtil.getUUID()+originalFilename.substring(originalFilename.indexOf("."), originalFilename.length());
                    path = temppath + File.separator + originalFilename;
                    out = new FileOutputStream(path);
                    out.write(myfile.getBytes());
                    filenames[1]="../temp/"+originalFilename;
                    filenames[2]=String.valueOf(myfile.getSize());
                    li.add(filenames);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                rst.setResultCode(ReqResult.resultCode_Success);
                rst.setReturnObject(li);
            }
        }
        return rst;
    }
    
    @RequestMapping(value="/delTempPic", produces = "text/plain;charset=UTF-8")
    public ReqResult delTempPic(HttpServletRequest request,@RequestParam(required=true)String path){
    	log.info("删除临时图片");
        ReqResult rst = new ReqResult();
        try{
        	String temppath = request.getSession().getServletContext().getRealPath("/");
        	if(path.indexOf("temp/")<0){
        		temppath=temppath+ "temp"+File.separator;
        	}
        	if(delFile(temppath+path)){
        		rst.setResultCode(ReqResult.resultCode_Success);
        	}
        }catch(Exception e){
        	log.error("删除临时图片异常",e);
        	rst.setResultCode(ReqResult.resultCode_error);
        	rst.setReturnObject("删除临时图片异常");
        }
        return rst;
    }
    
    public boolean delFile(String path){
		File file=new File(path);
		if(file.exists()&&file.isFile()){
			if(file.delete()){
				return true;
			}
			return false;
		}
		return false;
	}
    

    

    
    /**
	 * 文件下载
	 * @param theURL
	 * @param fname
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/downloadFile", produces = "text/plain;charset=UTF-8")
	public ReqResult downloadFile(String theURL,String fname,HttpServletRequest request,HttpServletResponse response){
		ReqResult rst = new ReqResult();
		URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            urlfile = new URL(theURL);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
 
          String  fileName = URLDecoder.decode(fname, "UTF-8");  
         fileName = URLEncoder.encode(fileName, "UTF-8");
         fileName = fileName.replace("+","%20");//还原空格
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);
           // response.reset();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(response.getOutputStream());

            try {
            	 int len = 2048;
                 byte[] b = new byte[2048];

                 while ((len = bis.read(b)) != -1){
                     bos.write(b, 0, len);
                 }
			} catch (Exception e) {
				log.info("空文件下载异常:url={}",theURL);
			}
            
            bos.flush();
            bis.close();
            httpUrl.disconnect();
            rst.setResultCode(ReqResult.resultCode_Success);
			return rst;
        }catch (Exception e) {
        	log.error("文件下载异常",e);
            rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("系统异常");
			return rst;
        }finally {
        	try{
        		bis.close();
        		bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
}
